﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using Service.Infrastructure.Implement;
using Service.Infrastructure.Result;
using SystmicFunction.Public.FileService;

namespace Service.Infrastructure
{
    /// <summary>
    ///     服务层容器
    /// </summary>
    public class BaseService
    {
        /// <summary>
        ///     初始化返回结果集合
        /// </summary>
        private ServiceResult _result;

        #region 返回值

        /// <summary>
        ///     友好性封装，作用于Controller,Filter的Service结果调用
        /// </summary>
        /// <param name="result">处理结果类型</param>
        /// <param name="reData"></param>
        public ServiceResult Result(ResultType result, Object reData)
        {
            _result = new BaseResult();
            _result.SetCode(result);
            
            _result.SetData(reData);
            return _result;
        }

        public ServiceResult Result(ResultType result)
        {
            return Result(result, null);
        }




        #endregion

        #region 参数




        /// <summary>
        ///     参数为空
        /// </summary>
        /// <param name="inParams">实体参数</param>
        /// <returns></returns>
        public bool ParamsIsNull(params Object[] inParams)
        {
            if (inParams.Any(ParamIsNullOrEmpty))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        ///     参数为空或者空初始
        /// </summary>
        /// <param name="inParam"></param>
        /// <returns></returns>
        private bool ParamIsNullOrEmpty(Object inParam)
        {
            if (inParam == null)
            {
                return true;
            }

            if (ReferenceEquals(inParam.GetType(), Type.GetType("System.Guid")))
            {
                return (Guid)inParam == Guid.Empty;
            }

            if (ReferenceEquals(inParam.GetType(), Type.GetType("System.String")))
            {
                return String.IsNullOrEmpty((string)inParam);
            }

            return false;
        }

        #endregion

        #region 图片


        /// <summary>
        ///     图片上传并保存
        /// </summary>
        /// <param name="context"></param>
        /// <param name="pathBase"></param>
        /// <returns></returns>
        public ServiceResult ImgUp(HttpContext context, String pathBase)
        {
            var imageSavePath = new[] { "upload1", "upload2", "upload3" };//TODO:图片保存路径，可以根据系统配置

            if (!String.IsNullOrEmpty(context.Request.QueryString["fetch"]))
            {

                context.Response.AddHeader("Content-Type", "text/javascript;charset=utf-8");
                return Result(ResultType.Success, String.Format("updateSavePath([{0}]);", String.Join(", ", imageSavePath.Select(x => "\"" + x + "\""))));
            }
            context.Response.AddHeader("Content-Type", "text/plain;charset=utf-8");

            //上传配置
            //const string pathbase = "upload"; //TODO:保存路径，可以根据系统配置
            //文件大小限制,单位mb
            const int size = 2; //TODO：根据系统配置                                                  
            //文件允许格式
            string[] fileType = FileHelper.ImgSuffixNames;

            string path = FileHelper.GetOtherInfo(context, "dir");
            if (String.IsNullOrEmpty(path))
            {
                path = imageSavePath[0];
            }
            else if (imageSavePath.Count(x => x == path) == 0)
            {
                //context.Response.Write();
                return Result(ResultType.ParamIsError, "{ 'state' : '非法上传目录' }");
            }
            //TODO：多个文件
            string state = "SUCCESS";//必须要为改值不能改其他的，不然JS插件认不到
            var upFile = FileHelper.Convert(context.Request.Files[0]);
            if (FileHelper.CheckType(upFile, fileType))
            {
                state = "图片类型不合法"; //TODO:验证码
            }
            if (FileHelper.CheckSize(upFile, size))
            {
                state = "尺寸不合法";
                //TODO:验证码
            }

            String url = FileHelper.HttpUploadFile(context, path);//TODO:非线程安全
            string title = FileHelper.GetOtherInfo(context, "pictitle");                   //获取图片描述
            string oriName = FileHelper.GetOtherInfo(context, "fileName");                //获取原始文件名

            //TODO：返回值处理

            return Result(ResultType.Success, "{'url':'" + url + "','title':'" + title + "','original':'" + oriName + "','state':'" + state + "'}");
        }

        /// <summary>
        ///     图片管理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public ServiceResult ImgMananger(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string[] paths = { "upload1", "upload2", "upload3" }; //需要遍历的目录列表，最好使用缩略图地址，否则当网速慢时可能会造成严重的延时
            string[] filetype = FileHelper.ImgSuffixNames;                //文件允许格式

            string action = context.Server.HtmlEncode(context.Request["action"]);

            if (action == "get")
            {
                String str = String.Empty;

                foreach (string path in paths)
                {
                    var info = new DirectoryInfo(HostingEnvironment.MapPath("~") + path);

                    //目录验证
                    if (info.Exists)
                    {
                        DirectoryInfo[] infoArr = info.GetDirectories();
                        str = infoArr.Aggregate(str, (current1, tmpInfo) => tmpInfo.GetFiles().Where(fi => Array.IndexOf(filetype, fi.Extension) != -1).Aggregate(current1, (current, fi) => current + (path + "/" + tmpInfo.Name + "/" + fi.Name + "ue_separate_ue")));
                    }
                }
                return Result(ResultType.Success, str);

            }
            return Result(ResultType.Success);
        }

        #endregion

    }

}